package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.wemedia.IWemediaClient;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class HotArticleServiceImpl implements HotArticleService {

    @Autowired
    private ApArticleMapper articleMapper;

    @Autowired
    private IWemediaClient wemediaClient;

    @Autowired
    private CacheService cacheService;

    /**
     * 计算热点文章
     */
    @Override
    public void computeHotArticle() {
        // 查询前五天发布的文章
        // 获取五天前的时间
        Date date = DateTime.now().minusDays(10).toDate();
        List<ApArticle> articleList = articleMapper.findArticleListByDays(date);

        // 计算文章的分数
        List<HotArticleVo> voList = computeHotArticleScore(articleList);

        // 将每个频道计算完得分的文章的前三十条数据添加到redis
        cacheTagToRedis(voList);

    }

    /**
     * 将热点文章添加到redis
     *
     * @param voList
     */
    private void cacheTagToRedis(List<HotArticleVo> voList) {
        // 查询出所有的频道
        ResponseResult responseResult = wemediaClient.getChannels();
        if (responseResult != null && responseResult.getCode() == 200) {
            // 获取到结果
            List<WmChannel> wmChannels = JSON.parseArray(JSON.toJSONString(responseResult.getData()), WmChannel.class);
            for (WmChannel wmChannel : wmChannels) {
                List<HotArticleVo> hotArticleVoList = voList.stream()
                        .filter(item -> wmChannel.getId().equals(item.getChannelId())) // 过滤出当前频道的
                        .sorted(Comparator.comparing(HotArticleVo::getScore).reversed()) // 反转排序,根据得分排序,降序
                        .limit(30) // 获取前三十条数据
                        .collect(Collectors.toList());

                // 将结果存储到redis中
                cacheService.set(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + wmChannel.getId(),
                        JSON.toJSONString(hotArticleVoList));
            }
        }

        // 添加首页推荐的数据
        List<HotArticleVo> hotArticleVos = voList.stream()
                .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                .limit(30)
                .collect(Collectors.toList());

        cacheService.set(ArticleConstants.HOT_ARTICLE_FIRST_PAGE+ArticleConstants.DEFAULT_TAG,
                JSON.toJSONString(hotArticleVos));
    }

    /**
     * 计算文章的得分
     *
     * @param articleList
     * @return
     */
    private List<HotArticleVo> computeHotArticleScore(List<ApArticle> articleList) {
        List<HotArticleVo> hotArticleVoList = articleList.stream().map(apArticle -> {
            HotArticleVo hotArticleVo = new HotArticleVo();
            // 属性拷贝
            BeanUtils.copyProperties(apArticle, hotArticleVo);

            // 计算得分
            Integer score = computeScore(apArticle);
            hotArticleVo.setScore(score);

            return hotArticleVo;
        }).collect(Collectors.toList());

        return hotArticleVoList;
    }

    /**
     * 计算文章的具体得分
     *
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        Integer score = 0;

        if (apArticle.getLikes() != null) {
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }

        if (apArticle.getViews() != null) {
            score += apArticle.getViews();
        }

        if (apArticle.getComment() != null) {
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }

        if (apArticle.getCollection() != null) {
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }

        return score;
    }
}
